<template>
  <div class="notice-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>公告列表</span>
          <el-button type="primary" @click="handleAddNotice"
            >添加公告</el-button
          >
        </div>
      </template>

      <div class="search-box">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="标题">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入公告标题"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="发布" :value="1" />
              <el-option label="草稿" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table v-loading="loading" :data="noticeList">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="标题" />
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? "已发布" : "草稿" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="是否置顶" width="80">
          <template #default="scope">
            <el-tag type="warning" v-if="scope.row.sort === 1">置顶</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? "下架" : "发布" }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="queryParams.page"
          :page-size="queryParams.limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getNoticeList, updateNotice, deleteNotice } from "@/api/notices";
import { useUserStore } from "@/store/user";

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const noticeList = ref([]);
const total = ref(0);

const queryParams = reactive({
  page: 1,
  limit: 10,
  title: "",
  status: "",
});

// 获取公告列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getNoticeList(queryParams);
    if (res.code === 0) {
      noticeList.value = res.data.list;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.message || "获取公告列表失败");
    }
  } catch (error) {
    console.error("获取公告列表失败", error);
    ElMessage.error("获取公告列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = () => {
  queryParams.page = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.title = "";
  queryParams.status = "";
  handleQuery();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val;
  getList();
};

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.limit = val;
  queryParams.page = 1;
  getList();
};

// 添加公告
const handleAddNotice = () => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("add:notice")) {
    ElMessage.warning("测试账号不能添加公告");
    return;
  }
  router.push("/notice/add");
};

// 编辑公告
const handleEdit = (row) => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("edit:notice")) {
    ElMessage.warning("测试账号不能编辑公告");
    return;
  }
  router.push(`/notice/edit/${row.id}`);
};

// 切换公告状态
const handleStatusChange = (row) => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("edit:notice")) {
    ElMessage.warning("测试账号不能修改公告状态");
    return;
  }

  const statusText = row.status === 1 ? "下架" : "发布";
  const newStatus = row.status === 1 ? 0 : 1;

  ElMessageBox.confirm(`确认要${statusText}该公告吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await updateNotice(row.id, { status: newStatus });
        if (res.code === 0) {
          ElMessage.success(`${statusText}成功`);
          getList();
        } else {
          ElMessage.error(res.message || `${statusText}失败`);
        }
      } catch (error) {
        console.error(`${statusText}失败`, error);
        ElMessage.error(`${statusText}失败`);
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 删除公告
const handleDelete = (row) => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("delete:notice")) {
    ElMessage.warning("测试账号不能删除公告");
    return;
  }

  ElMessageBox.confirm(`确认要删除公告 "${row.title}" 吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteNotice(row.id);
        if (res.code === 0) {
          ElMessage.success("删除成功");
          getList();
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.notice-list-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-box {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
